import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCInsertExercise {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);

        //1.创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("111111");

        // 2.和数据库服务器进行链接
        Connection connection = dataSource.getConnection();

        // 3. 构造sql语句
        System.out.println("请输入序号：");
        int id = scanner.nextInt();

        System.out.println("请输入姓名：");
        String name = scanner.nextLine();

        String sql = "insert into student (id,name) values (?,?)";   //这里的问好是一个占位符号
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);

        System.out.println(statement);
        // 4.执行sql语句
        int ret = statement.executeUpdate();
        System.out.println(ret);

        // 5.释放必要的资源
        statement.close();  //谁是后创建的 谁就先释放，相当于倒回去  先释放语句 后释放连接
        connection.close();
    }
}
